package com.example.chess.widgets;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.example.chess.utils.Utils;

/**
 * Created by xuyougen.
 * 获胜率展示条
 */
public class RateView extends View {

    private float rate1, rate2;

    private float edgeOffset;
    private float borderWidth;
    private Paint paint;

    public RateView(Context context) {
        this(context, null);
    }

    public RateView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RateView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize();
    }

    private void initialize() {
        rate1 = rate2 = .5f;
        edgeOffset = Utils.dp2px(3f);
        borderWidth = Utils.dp2px(1f);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

    }

    public void setCount(int count1, int count2) {
        if (count1 == count2) {
            rate1 = rate2 = .5f;
        } else {
            int sum = count1 + count2;
            rate1 = count1 * 1f / sum;
            rate2 = count2 * 1f / sum;
        }
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {

        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.BLACK);
        float top = edgeOffset;
        float bottom = getHeight() - edgeOffset;
        float rate1Left = edgeOffset;
        float usableWidth = getWidth() - edgeOffset * 2;
        float rate1Right = rate1Left + usableWidth * rate1;

        canvas.drawRect(rate1Left, top, rate1Right, bottom, paint);
        paint.setColor(Color.GRAY);
        canvas.drawRect(rate1Right, top, getWidth()-edgeOffset, bottom, paint);

        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(borderWidth);
        float borderOffset = borderWidth/2f;
        canvas.drawRect(borderOffset,borderOffset,getWidth()-borderOffset,getHeight()-borderOffset,paint);
    }
}
